// pages/messages/messages.js
const { get, post, del } = require('../../utils/api.js')
const { showError, showSuccess, showToast } = require('../../utils/util.js')
const { navigateTo, switchTab } = require('../../utils/router.js')

Page({
  data: {
    // 搜索和筛选
    searchKeyword: '',
    activeFilter: 'all',
    
    // 数据列表
    conversations: [],
    filteredConversations: [],
    
    // 统计数据
    unreadCount: 0,
    newMatchCount: 0,
    
    // 加载状态
    loading: false,
    refreshing: false,
    hasMore: true,
    
    // 操作弹窗
    showActionSheet: false,
    actionSheetActions: [],
    selectedConversationId: '',
    
    // 删除确认
    showDeleteDialog: false,
    
    // 当前用户ID
    currentUserId: '',
    
    // 破冰话题建议
    iceBreakerSuggestions: [
      "你好！很高兴认识你 😊",
      "你的头像很有趣，是你自己设计的吗？",
      "我们有很多共同兴趣呢！",
      "今天天气不错，你在做什么呢？",
      "你最喜欢的休闲活动是什么？",
      "我们的兼容度很高呢，想聊聊吗？"
    ],
    showIceBreakerDialog: false,
    selectedIceBreaker: '',
    
    // 消息增强功能
    showMessageActions: false,
    messageActionsData: null,
    
    // 语音消息支持
    voiceMessageSupport: true,
    
    // 消息状态跟踪
    messageStatusMap: new Map(),
    
    // 实时更新
    messageUpdateTimer: null,
    lastUpdateTime: null
  },

  onLoad() {
    this.initPage()
  },

  onShow() {
    // 页面显示时刷新消息
    this.loadConversations()
  },

  /**
   * 初始化页面
   */
  initPage() {
    // 获取当前用户ID
    const app = getApp()
    const userInfo = app.getUserInfo()
    if (userInfo) {
      this.setData({
        currentUserId: userInfo.userId
      })
    }
    
    this.loadConversations()
  },

  /**
   * 加载会话列表
   */
  loadConversations() {
    this.setData({ loading: true })
    
    get('/api/messages/conversations')
      .then(data => {
        const conversations = data.conversations || []
        
        // 计算统计数据
        const unreadCount = conversations.reduce((count, conv) => count + conv.unreadCount, 0)
        const newMatchCount = conversations.filter(conv => conv.isNewMatch).length
        
        this.setData({
          conversations,
          unreadCount,
          newMatchCount,
          loading: false,
          refreshing: false
        })
        
        // 应用当前筛选
        this.applyFilter()
      })
      .catch(error => {
        console.error('加载会话列表失败:', error)
        this.setData({ 
          loading: false,
          refreshing: false 
        })
        showError('加载消息失败，请重试')
      })
  },

  /**
   * 搜索输入
   */
  onSearchInput(e) {
    const searchKeyword = e.detail.value
    this.setData({ searchKeyword })
    this.applyFilter()
  },

  /**
   * 筛选切换
   */
  onFilterChange(e) {
    const activeFilter = e.currentTarget.dataset.filter
    this.setData({ activeFilter })
    this.applyFilter()
  },

  /**
   * 应用筛选
   */
  applyFilter() {
    const { conversations, activeFilter, searchKeyword } = this.data
    let filtered = [...conversations]
    
    // 按筛选条件过滤
    switch (activeFilter) {
      case 'unread':
        filtered = filtered.filter(conv => conv.unreadCount > 0)
        break
      case 'matches':
        filtered = filtered.filter(conv => conv.isNewMatch)
        break
      case 'all':
      default:
        // 不过滤
        break
    }
    
    // 按关键词搜索
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase()
      filtered = filtered.filter(conv => {
        return conv.user.nickname.toLowerCase().includes(keyword) ||
               (conv.lastMessage.content && conv.lastMessage.content.toLowerCase().includes(keyword))
      })
    }
    
    this.setData({ filteredConversations: filtered })
  },

  /**
   * 下拉刷新
   */
  onRefresh() {
    this.setData({ refreshing: true })
    this.loadConversations()
  },

  /**
   * 加载更多
   */
  onLoadMore() {
    // TODO: 实现分页加载
    console.log('加载更多会话')
  },

  /**
   * 进入聊天页面
   */
  enterChat(e) {
    const { conversationId, userId } = e.currentTarget.dataset
    
    // 标记为已读
    this.markAsRead(conversationId)
    
    // 跳转到聊天页面
    navigateTo(`/pages/chat/chat?userId=${userId}&conversationId=${conversationId}`)
  },

  /**
   * 快速发送破冰话题
   */
  showIceBreakerDialog(e) {
    e.stopPropagation() // 阻止事件冒泡
    const conversationId = e.currentTarget.dataset.conversationId
    const userId = e.currentTarget.dataset.userId
    
    this.setData({
      showIceBreakerDialog: true,
      selectedConversationId: conversationId,
      messageActionsData: { userId, conversationId }
    })
  },

  /**
   * 选择破冰话题
   */
  selectIceBreaker(e) {
    const suggestion = e.currentTarget.dataset.suggestion
    this.setData({ selectedIceBreaker: suggestion })
  },

  /**
   * 发送破冰话题
   */
  sendIceBreaker() {
    const { selectedIceBreaker, messageActionsData } = this.data
    
    if (!selectedIceBreaker || !messageActionsData) {
      showError('请选择一个话题')
      return
    }
    
    // 发送消息
    post('/api/messages/send', {
      conversationId: messageActionsData.conversationId,
      receiverId: messageActionsData.userId,
      type: 'text',
      content: selectedIceBreaker
    })
      .then(() => {
        showToast('消息已发送')
        this.hideIceBreakerDialog()
        
        // 跳转到聊天页面
        navigateTo(`/pages/chat/chat?userId=${messageActionsData.userId}&conversationId=${messageActionsData.conversationId}`)
      })
      .catch(error => {
        console.error('发送破冰话题失败:', error)
        showError('发送失败，请重试')
      })
  },

  /**
   * 隐藏破冰话题对话框
   */
  hideIceBreakerDialog() {
    this.setData({
      showIceBreakerDialog: false,
      selectedIceBreaker: '',
      messageActionsData: null
    })
  },

  /**
   * 显示消息快捷操作
   */
  showMessageActions(e) {
    e.stopPropagation() // 阻止事件冒泡
    const conversationId = e.currentTarget.dataset.conversationId
    const userId = e.currentTarget.dataset.userId
    const conversation = this.data.conversations.find(conv => conv.conversationId === conversationId)
    
    if (!conversation) return
    
    const actions = [
      {
        name: 'chat',
        text: '进入聊天',
        color: '#ff6b9d'
      },
      {
        name: 'icebreaker',
        text: '发送破冰话题',
        color: '#00d4aa'
      },
      {
        name: 'profile',
        text: '查看资料',
        color: '#3b82f6'
      }
    ]
    
    this.setData({
      showMessageActions: true,
      messageActionsData: { userId, conversationId, conversation },
      actionSheetActions: actions
    })
  },

  /**
   * 处理消息操作
   */
  onMessageAction(e) {
    const { name } = e.detail
    const { messageActionsData } = this.data
    
    switch (name) {
      case 'chat':
        this.enterChat({ currentTarget: { dataset: messageActionsData } })
        break
      case 'icebreaker':
        this.showIceBreakerDialog({ currentTarget: { dataset: messageActionsData }, stopPropagation: () => {} })
        break
      case 'profile':
        navigateTo(`/pages/user-detail/user-detail?userId=${messageActionsData.userId}`)
        break
    }
    
    this.hideMessageActions()
  },

  /**
   * 隐藏消息操作
   */
  hideMessageActions() {
    this.setData({
      showMessageActions: false,
      messageActionsData: null
    })
  },

  /**
   * 显示会话操作菜单
   */
  showConversationMenu(e) {
    const conversationId = e.currentTarget.dataset.conversationId
    const conversation = this.data.conversations.find(conv => conv.conversationId === conversationId)
    
    if (!conversation) return
    
    const actions = [
      {
        name: 'pin',
        text: conversation.isPinned ? '取消置顶' : '置顶聊天',
        color: '#ffa500'
      },
      {
        name: 'mute',
        text: conversation.isMuted ? '取消免打扰' : '免打扰消息',
        color: '#666'
      },
      {
        name: 'delete',
        text: '删除会话',
        color: '#ff3b30'
      }
    ]
    
    this.setData({
      showActionSheet: true,
      actionSheetActions: actions,
      selectedConversationId: conversationId
    })
  },

  /**
   * 操作菜单选择
   */
  onActionSelect(e) {
    const { name } = e.detail
    const { selectedConversationId } = this.data
    
    switch (name) {
      case 'pin':
        this.pinConversation(selectedConversationId)
        break
      case 'mute':
        this.muteConversation(selectedConversationId)
        break
      case 'delete':
        this.setData({ showDeleteDialog: true })
        return // 不隐藏 ActionSheet，等待用户确认
    }
    
    this.hideActionSheet()
  },

  /**
   * 隐藏操作菜单
   */
  hideActionSheet() {
    this.setData({
      showActionSheet: false,
      selectedConversationId: ''
    })
  },

  /**
   * 置顶会话
   */
  pinConversation(conversationId) {
    const conversation = this.data.conversations.find(conv => conv.conversationId === conversationId)
    if (!conversation) return
    
    const action = conversation.isPinned ? 'unpin' : 'pin'
    
    post(`/api/messages/${action}-conversation`, { conversationId })
      .then(() => {
        // 更新本地状态
        conversation.isPinned = !conversation.isPinned
        this.setData({ conversations: this.data.conversations })
        this.applyFilter()
        
        showToast(conversation.isPinned ? '已置顶' : '已取消置顶')
      })
      .catch(error => {
        console.error('置顶操作失败:', error)
        showError('操作失败，请重试')
      })
  },

  /**
   * 免打扰会话
   */
  muteConversation(conversationId) {
    const conversation = this.data.conversations.find(conv => conv.conversationId === conversationId)
    if (!conversation) return
    
    const action = conversation.isMuted ? 'unmute' : 'mute'
    
    post(`/api/messages/${action}-conversation`, { conversationId })
      .then(() => {
        // 更新本地状态
        conversation.isMuted = !conversation.isMuted
        this.setData({ conversations: this.data.conversations })
        this.applyFilter()
        
        showToast(conversation.isMuted ? '已免打扰' : '已取消免打扰')
      })
      .catch(error => {
        console.error('免打扰操作失败:', error)
        showError('操作失败，请重试')
      })
  },

  /**
   * 确认删除会话
   */
  confirmDelete() {
    const { selectedConversationId } = this.data
    
    del('/api/messages/conversation', { conversationId: selectedConversationId })
      .then(() => {
        // 从本地列表中移除
        const conversations = this.data.conversations.filter(
          conv => conv.conversationId !== selectedConversationId
        )
        
        this.setData({ 
          conversations,
          showDeleteDialog: false,
          selectedConversationId: ''
        })
        
        this.applyFilter()
        this.hideActionSheet()
        showToast('已删除会话')
      })
      .catch(error => {
        console.error('删除会话失败:', error)
        showError('删除失败，请重试')
      })
  },

  /**
   * 取消删除
   */
  cancelDelete() {
    this.setData({ showDeleteDialog: false })
    this.hideActionSheet()
  },

  /**
   * 标记为已读
   */
  markAsRead(conversationId) {
    post('/api/messages/mark-read', { conversationId })
      .then(() => {
        // 更新本地未读数
        const conversation = this.data.conversations.find(conv => conv.conversationId === conversationId)
        if (conversation && conversation.unreadCount > 0) {
          const unreadCount = this.data.unreadCount - conversation.unreadCount
          conversation.unreadCount = 0
          
          this.setData({ 
            conversations: this.data.conversations,
            unreadCount: Math.max(0, unreadCount)
          })
          
          this.applyFilter()
        }
      })
      .catch(error => {
        console.error('标记已读失败:', error)
      })
  },

  /**
   * 跳转到发现页
   */
  goToDiscover() {
    switchTab('/pages/discovery/discovery')
  },

  /**
   * 分享页面
   */
  onShareAppMessage() {
    return {
      title: '青鸟笺 - 用心灵相遇，让真爱绽放',
      path: '/pages/discovery/discovery',
      imageUrl: '../../images/share-messages.png'
    }
  }
})